<template>
  <div class="cesium_map">
    <div :id="container" class="cesiumContainer"></div>
  </div>
</template>
<script>
import DrawTool from './utils/DrawTool';
import BasicTool from './utils/BasicTool';
import MarkerTool from './utils/MarkerTool';
import MapTileTool from './utils/MapTileTool';

export default {
  props: {
    container: String,
    mapOpt: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  name: 'ddCesium',
  data() {
    return {
      viewer: null,
      postRender: null,
      mapOptions: {
        center: [112.036125, 25.685413, 10000],
        enableCompass: true, //用于启用或禁用罗盘
        enableZoomControls: true, //用于启用或禁用缩放控件
        enableDistanceLegend: true, //用于启用或禁用距离图例
        enableCompassOuterRing: true, //用于启用或禁用指南针外环
        minimumZoomDistance: 100,
        maximumZoomDistance: 55000000,
      },
      drawTool: null,
      basicTool: null,
      markerTool: null,
      tempEntities: [],

      leftDownFlag: false,
      pointDraged: null,
    };
  },
  created() {},
  mounted() {
    this.init().then((res) => {
      //阻止浏览器默认的右键事件
      document.oncontextmenu = function () {
        return false;
      };
      this.$emit('initMapFinish');
    });
  },
  methods: {
    // 初始化
    init() {
      return new Promise((resolve, reject) => {
        // 合并选项
        this.mapOptions = Object.assign({}, this.mapOptions, this.mapOpt);
        console.log('mapOption', this.mapOptions);
        // 引入个人token 是要自己去官网注册获取 https://ion.cesium.com/
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNjg0ZDExMC1lN2I1LTQzZWUtYTNkYS0zM2RiMmVkMmM4YWMiLCJpZCI6NTk0MDcsImlhdCI6MTYyNDA5ODA3Mn0.UXQ22aUZ7svxLMU62jxRXLRJXAPE0HT3Dw2wDB7Y6eU';
        this.viewer = new Cesium.Viewer(this.container, {
          geocoder: false, //查找位置工具
          homeButton: false, //返回初始位置
          infoBox: false, //是否显示信息框
          sceneModePicker: false, //选择视角的工具。3D/2D/2.5D
          baseLayerPicker: false, //影像底图
          navigationHelpButton: false, //导航帮助按钮，显示默认的地图帮助
          animation: false, //动画器件，控制动画的播放速度
          selectionIndicator: false, //是否显示选取指示器组件
          timeline: false, //时间线
          scene3DOnly: false, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
          navigationInstructionsInitiallyVisible: false,
          imageryProvider: new Cesium.SingleTileImageryProvider({
            url: require('./images/0.jpg'),
            maximumLevel: 22,
            //rectangle: rectangle
            //url: "../../Cesium/Assets/Textures/NaturalEarthII/0/0/0.jpg"
          }),
          contextOption: {
            webgl: {
              alpha: true,
              depth: true,
              stencil: true,
              antialias: true,
              premultipliedAlpha: true,
              //通过canvas.toDataURL()实现截图需要将该项设置为true
              preserveDrawingBuffer: true,
              failIfMajorPerformanceCaveat: true,
            },
          },
          // mapMode2D: Cesium.MapMode2D.ROTATE,y
          fullscreenButton: false, //全屏按钮
          // mapProjection: new Cesium.WebMercatorProjection(), //地图投影体系
          // shadows: true, //阴影
          // 地形提供商
          terrainProvider: Cesium.createWorldTerrain({
            //url : 'https://data.marsgis.cn/terrain/',
            //url : 'https://assets.agi.com/stk-terrain/world',
            // 光照阴影
            requestVertexNormals: false,
            // 水流效果
            requestWaterMask: false,

            // requestVertexNormals: false,
            // requestWaterMask: false,
            // requestMetadata: false,
            // enableLighting: false,
            // asynchronous: false
          }),

          // terrainProvider: new Cesium.ArcGISTiledElevationTerrainProvider({
          //     url: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer",
          // }),
        });

        // viewer = this.viewer;
        //使用太阳作为光源，可以照亮地球。
        this.viewer.scene.globe.enableLighting = false;
        //关闭地面大气效果，（默认为开启状态）
        this.viewer.scene.globe.showGroundAtmosphere = false;
        //FPS 帧率显示
        this.viewer.scene.debugShowFramesPerSecond = false;
        //cesiumCanvas id 设置
        this.viewer.scene.canvas.id = 'cesiumCanvas';
        // 去除版权信息
        this.viewer._cesiumWidget._creditContainer.style.display = 'none';

        //限制缩放级别  (设置观看最低、最高高度)
        if (this.mapOptions.maximumZoomDistance) {
          this.viewer.scene.screenSpaceCameraController.maximumZoomDistance = this.mapOptions.maximumZoomDistance;
        }
        if (this.mapOptions.minimumZoomDistance) {
          //越大则缩小看到的全局范围越广。默认缩小至刚好看到整个佛山底图的距离
          this.viewer.scene.screenSpaceCameraController.minimumZoomDistance = this.mapOptions.minimumZoomDistance;
        }

        this.removeCluterListener = undefined; //聚合事件
        this.deviceEntities = []; //设备实体对象数组
        //使用自定义dataSource，后面使用cesium自带聚合功能需要用到
        this.deviceDataSource = new Cesium.CustomDataSource('deviceLayer');
        //viewer的dataSources属性加入dataSource
        this.deviceDataSourcePromise = this.viewer.dataSources.add(this.deviceDataSource);
        // 初始化工具
        this.basicTool = new BasicTool(this.viewer);
        // this.basicTool.openDepthTestAgainstTerrain();
        // 画图工具
        this.drawTool = new DrawTool(this.viewer);
        // 点位工具
        this.markerTool = new MarkerTool(this.viewer);
        // 地图底图工具类
        this.mapTileTool = new MapTileTool(this.viewer);
        // 定位到中心点
        this.basicTool.goToInit(this.mapOptions.center);
        // 加载离线地图
        this.mapTileTool.loadLocalTile('huilong' + '/{z}/{x}/{y}.png', 'img', 'local');
        // var tileset_url =
        //      '../SampleData/Cesium3DTiles/Tilesets/Tileset/tileset.json';
        // 加载三维模型
        var tileset_url = 'sanwei/tileset.json';
        if (process.env.NODE_ENV === 'production') {
          this.mapTileTool.load3DTile(
            tileset_url,
            0,
            function () {
              console.log('3DTile 加载成功...');
            },
            function () {
              console.log('3DTile 加载中...');
            },
          );
        }

        this.initEvent();
        resolve(this.viewer);
      }).catch((error) => {
        console.log(error);
      });
    },
    // 鼠标事件
    initEvent() {
      let _this = this;
      var handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas);
      var scene = this.viewer.scene;
      //右键按下事件
      handler.setInputAction(function (event) {
        // 判断是否是点击在实体上
        let pickedObject = _this.basicTool.pickEntity(event.position);
        _this.$emit('rightDownEvent', event, pickedObject);
        // _this.viewer.scene.screenSpaceCameraController.enableRotate = true; //锁定相机
      }, Cesium.ScreenSpaceEventType.RIGHT_DOWN);
      //右键抬起事件
      handler.setInputAction(function (event) {
        _this.$emit('rightUpEvent', event);
      }, Cesium.ScreenSpaceEventType.RIGHT_UP);
      //鼠标移动事件
      handler.setInputAction(function (event) {
        if (_this.leftDownFlag === true && _this.pointDraged != null) {
          console.log('鼠标移动');
          let ray = _this.viewer.camera.getPickRay(event.endPosition);
          let cartesian = _this.viewer.scene.globe.pick(ray, _this.viewer.scene);
          var stringLonLatArr = _this.basicTool.cartesian2ArrayLonLat(cartesian);
          _this.pointDraged.id.position = new Cesium.CallbackProperty(function () {
            return cartesian;
          }, false); //此处根据具体entity来处理，也可能是pointDraged.id.position=cartesian;
        }
        _this.$emit('mouseMoveEvent', event, stringLonLatArr);
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      //左键按下事件
      handler.setInputAction(function (event) {
        console.log('左键按下');
        _this.pointDraged = _this.viewer.scene.pick(event.position); //选取当前的entity
        // _this.leftDownFlag = true;
        if (_this.pointDraged) {
          _this.viewer.scene.screenSpaceCameraController.enableRotate = false; //锁定相机
        }
        _this.$emit('leftDownEvent', event);
      }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
      //左键抬起事件
      handler.setInputAction(function (event) {
        console.log('左键抬起');
        _this.leftDownFlag = false;
        _this.pointDraged = null;
        _this.viewer.scene.screenSpaceCameraController.enableRotate = true; //解锁相机
        let pickedObject = _this.basicTool.pickEntity(event.position);
        _this.$emit('leftUpEvent', event, pickedObject);
      }, Cesium.ScreenSpaceEventType.LEFT_UP);

      // 实时监听事件
      this.postRender = scene.postRender.addEventListener(function (event) {
        _this.$emit('postRenderEvent', event);
      }, this);
    },
    // 关闭监听器
    closeRender() {
      this.viewer.scene.postRender.removeEventListener(this.postRender, this); //移除事件监听
    },
    entityShow(id) {
      this.$emit('initShowByIds', id);
      console.log('emit entity show id:', id);
    },
    entityDelete(id) {
      this.$emit('initDeleteByIds', id);
      console.log('emit entity delete id:', id);
    },
  },
};
</script>
<style lang="scss" scoped>
.cesium_map {
  font-size: 20px;
  width: 100%;
  height: 100%;
  #map {
    height: 100%;
  }
  .cesiumContainer {
    width: 100%;
    height: 100%;
    // .contextmenu{
    //   .contextmenu-ul{
    //     background: rgb(171 247 87 / 50%);
    //     padding: 8px;
    //     border-radius: 5px;
    //   }
    // }
  }
}
</style> 
